package com.enqualcomm.kids.network;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.http.ReaiRequest;
import com.enqualcomm.kids.BuildConfig;
import com.enqualcomm.kids.config.StateCode;
import com.enqualcomm.kids.network.http.request.BasicParams;
import com.enqualcomm.kids.network.http.response.BasicResult;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import common.utils.GsonFactory;
import common.utils.MyLogger;

/**
 * Created by yinzhiqun on 2015/9/8.
 *
 */
public class HttpRequest <T extends BasicResult> extends Request<T> implements ReaiRequest {

    private NetworkListener<T> mListener;
    private final BasicParams params;

    public HttpRequest(BasicParams p,NetworkListener<T> listener) {
        super(Method.POST, BuildConfig.API_URL, null);
//        super(Method.POST, "http://192.168.1.199:8080", null);
        mListener = listener;
        params = p;
        setShouldCache(false);//不需要缓存
//        setRetryPolicy(new DefaultRetryPolicy());设置连接超时，默认2500毫秒
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("cmd", params.getCmd());
        headers.put("version",params.getVersion());
        headers.put("licence",BuildConfig.LICENCE);
        return headers;
    }

    @Override
    public String getJson() {
        String json = GsonFactory.newInstance().toJson(params);
//        MyLogger.jLog().i(params.getCmd()+": "+json);//TODO
        return json;
    }

    @Override
    public File getFile() {
        return params.getFile();
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        if (response.statusCode==200){
            try {
                EntityDecoder decoder = new EntityDecoder().decode(response.data);
                T t = null;

                if (decoder.stateCode == StateCode.OK){
//                    MyLogger.jLog().i(params.getCmd()+", "+decoder.json);
                    if (params.getResponsePojo()!=BasicResult.class){
                        t = GsonFactory.newInstance().fromJson(decoder.json, params.getResponsePojo());
                        //t.code = StateCode.OK;默认就是0
                        t.file = decoder.file;
                    }else{
                        t = GsonFactory.newInstance().fromJson(String.format("{\"code\":%d}",decoder.stateCode)
                                , params.getResponsePojo());
                    }
                }else {//返回状态码不是0
//                    MyLogger.jLog().i(params.getCmd()+", ErrorCode: "+decoder.stateCode);

                    t = GsonFactory.newInstance().fromJson(String.format("{\"code\":%d}",decoder.stateCode)
                            , params.getResponsePojo());
                }
                return Response.success(t, null);//业务层错误也放到onSuccess里面处理
            } catch (ParseError parseError) {
                parseError.printStackTrace();

                return Response.error(parseError);//解析错误
            }
        }else {
            return Response.error(new NetworkError());
        }
    }

    @Override
    protected void deliverResponse(T response) {
        if (mListener!=null){
            mListener.onSuccess(response);
        }
    }

    @Override
    public void deliverError(VolleyError error) {
        if (mListener!=null) {
            mListener.onError(error);
        }
    }

    @Override
    protected void onFinish() {
        mListener = null;
    }

}
